﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using BlockMain_Class;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using Newtonsoft.Json;

namespace WebApplication.Controllers
{
    public class ShowController : Controller
    {
        private IHostingEnvironment hostingEnv;


        public ShowController(IHostingEnvironment env)
        {
            this.hostingEnv = env;
        }

        public IActionResult Index()
        {
            string value = "";
            HttpContext.Request.Cookies.TryGetValue("user", out value);
            //获取登录信息
            var user = GetUser.GetUserInfo(value);
            if (user != null)
            {
                return View(user);
            }
            else
            {
                return Redirect("/login");
            }
        }

        /// <summary>
        /// 提交数据 本地记录
        /// </summary>
        /// <returns></returns>
        public ActionResult Add(string Mechanism, int Type, string[] Project, int[] IsQualified, string TestMechanism, DateTime[] SuceessTime)
        {
            string value = "";
            HttpContext.Request.Cookies.TryGetValue("user", out value);
            //获取登录信息
            var user = GetUser.GetUserInfo(value);
            //保存记录
            var thisrecord = new BlockRecords();

            thisrecord.Mechanism = Mechanism;
            thisrecord.TestMechanism = user.account;
            thisrecord.NowPeer = user.id;
            thisrecord.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            thisrecord.Type = Type;
            //file
            //文件
            var files = Request.Form.Files;
            if (files[0].Length > 0)
            {
                //存在文件
                var file = files[0];
                var filename = ContentDispositionHeaderValue
                     .Parse(file.ContentDisposition)
                     .FileName
                     .Trim('"');
                var path = filename;
                filename = hostingEnv.WebRootPath + $@"\{filename}";
                using (FileStream fs = System.IO.File.Create(filename))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                thisrecord.FilePath = path;// filename;
            }
            //项目信息
            //项目信息 用于展示
            var userrecord = new UserRecordJson();
            userrecord.Mechanism = Mechanism;
            userrecord.TestMechanism = TestMechanism;
            userrecord.NowPeer = user.id;
            userrecord.AddTime = thisrecord.CreateTime;
            userrecord.Type = Type;
            userrecord.FilePath = thisrecord.FilePath;
            List<UserRecordJsonItem> lu = new List<UserRecordJsonItem>();
            for (int i = 0; i < Project.Length; i++)
            {
                UserRecordJsonItem u = new UserRecordJsonItem();
                u.Name = Project[i];
                u.IsQualified = IsQualified[i] == 1;
                u.SuceessTime = SuceessTime[i].ToString("yyyy-MM-dd");
                lu.Add(u);
            }
            userrecord.ProjecItem = lu;
            var jsonstr = JsonConvert.SerializeObject(userrecord);
            thisrecord.JsonData = jsonstr;
            //保存
            MongodbHelpers<BlockRecords> mon = new MongodbHelpers<BlockRecords>();
            var savaresult = mon.Insert(thisrecord);

            //入链操作 
            var data = "peerid=" + user.id + "&data=" + jsonstr;
            var resule = HttpHelper.PostWebRequest("http://localhost:112/addblock/add", data);
            //序列化
            if (!string.IsNullOrEmpty(resule))
            {
                Messages b = JsonConvert.DeserializeObject<Messages>(resule);
                if (b.state == 200)
                {
                    //请求成功
                    return Redirect("/Show/Info?rid=" + savaresult.Id.ToString());
                }
                else
                {
                    return Content(b.msg);
                }
            }
            return null;
        }



        /// <summary>
        /// 入库详情
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>

        public ActionResult Info(string rid)
        {
            MongodbHelpers<BlockRecords> mon = new MongodbHelpers<BlockRecords>();
            var nowinfo = mon.QueryOne(rid);
            info i = new info();
            i.rid = rid;
            i.AddTime = nowinfo.CreateTime;
            i.FilePath = nowinfo.FilePath;
            i.Mechanism = nowinfo.Mechanism;
            i.NowPeer = nowinfo.NowPeer;
            i.Type = nowinfo.Type;
            i.TestMechanism = nowinfo.TestMechanism;
            var peoject = JsonConvert.DeserializeObject<UserRecordJson>(nowinfo.JsonData);
            i.ProjecItem = peoject.ProjecItem;
            //获取进度
            return View(i);
        }


        /// <summary>
        /// 获取项目进度
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        public ActionResult GetSpeed(string rid)
        {
            //MongodbHelpers<Speed> spdeed = new MongodbHelpers<Speed>();
            //暂时写死
            List<Speed> ls = new List<Speed>();
            Speed s1 = new Speed(); s1.Detail = "入链申请已提交,合约正在验证"; s1.Sort = 1; s1.Record = rid; ls.Add(s1);
            Speed s2 = new Speed(); s2.Detail = "验证通过,即将广播到节点"; s2.Sort = 2; s2.Record = rid; ls.Add(s2);
            Speed s3 = new Speed(); s3.Detail = "节点已收到,正在处理"; s3.Sort = 3; s3.Record = rid; ls.Add(s3);
            Speed s4 = new Speed(); s4.Detail = "正在统一结果"; s4.Sort = 4; s4.Record = rid; ls.Add(s4);
            Speed s5 = new Speed(); s5.Detail = "恭喜你,入链成功"; s5.Sort = 5; s5.Record = rid; ls.Add(s5);
            var list = ls.Where(a => a.Record == rid).OrderBy(a => a.Sort).ToList();
            return Json(list);
        }

        /// <summary>
        /// 节点详情
        /// </summary>
        /// <param name="hash"></param>
        /// <returns></returns>
        public ActionResult PeerSelect(string Id)
        {
            MongodbHelpers<PeerList> peer = new MongodbHelpers<PeerList>();
            var item = peer.QueryOne(Id);
            PeerSelect s = new PeerSelect();
            if (item != null)
            {

                s.Msg = "ok";
                s.name = item.Account;
                s.Ip = item.PeerIp;
                s.detail = item.Detail;
                s.addtime = item.CreateTime;
                //获取数据
                List<BlockItem> lb = new List<BlockItem>();
                //获取对应节点数据
                var resule = HttpHelper.PostWebRequest("http://localhost:112/getblock/BackupPeerInfo", "id=" + Id);
                //序列化
                if (resule != null)
                {
                    var PeerInfo = JsonConvert.DeserializeObject<PeerInfo>(resule);
                    var index = 0;
                    foreach (var items in PeerInfo.Blocks)
                    {
                        if (items.Heigth > index)
                        {
                            index = items.Heigth;
                        }
                        BlockItem pli = new BlockItem();
                        pli.Heigth = items.Heigth;
                        pli.Hash = items.Hash;
                        pli.addtime = items.addtime;
                        pli.PrevHash = items.PrevHash;
                        lb.Add(pli);
                    }
                    s.Blocks = lb;
                    MongodbHelpers<AccountBook> block = new MongodbHelpers<AccountBook>();
                    var lastOrDefault = block.QueryAll().OrderByDescending(a => a.Id).First();
                    if (lastOrDefault != null)
                    {
                        var heigth = lastOrDefault.Height;
                        s.state = index == heigth ? 0 : 1;
                    }
                }
                return View(s);
                //return Json(, JsonRequestBehavior.AllowGet);
            }
            else
            {
                s.Msg = "null";
                return View(s);
            }

        }



        /// <summary>
        /// 公共查询页
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        public ActionResult Select(string hash = "")
        {
            //获取对应节点数据
            var resule = HttpHelper.PostWebRequest("http://localhost:112/getblock/BackupBlcokInfo", "hash=" + hash);
            SelectBlock s = new SelectBlock();
            if (resule != null)
            {
                var accbook = JsonConvert.DeserializeObject<AccountBook>(resule);
                if (accbook.Data == null)
                {
                    s.Msg = "null";
                    return View(s);
                }

                s.Msg = "ok";
                var mess = JsonConvert.DeserializeObject<UserRecordJson>(accbook.Data);
                s.Hash = accbook.Hash;
                s.TypeName = mess.Type == 0 ? "实验室" : mess.Type == 1 ? "电站" : "监造";
                s.OrderAddTime = mess.AddTime;//提交时间
                s.Mechanism = mess.Mechanism;
                s.TestMechanism = mess.TestMechanism;
                //区块信息
                s.Heigth = accbook.Height;
                s.AddTime = ToDate.To(accbook.TimeStamp).ToString("yyyy-MM-dd HH:mm:ss");
                s.PrevHash = accbook.PrevHash;
                s.FilePath = mess.FilePath;
                //共识状态
                List<PeerState> lp = new List<PeerState>();
                MongodbHelpers<PeerList> peer = new MongodbHelpers<PeerList>();
                var peerlist = peer.QueryAll();
                foreach (var peerList1 in peerlist)
                {
                    PeerState p = new PeerState();
                    p.name = peerList1.Account;
                    p.time = accbook.CreateTime;
                    p.state = 0;
                    lp.Add(p);
                }
                s.PeerState = lp;
                s.ProjecItem = mess.ProjecItem;
                s.NowPeer = mess.NowPeer;
                var peerList = peer.QueryOne(mess.NowPeer);
                if (peerList != null) s.NowPeerUrl = peerList.PeerUrl;
                return View(s);
            }
            else
            {
                s.Msg = "null";
                return View(s);
            }
        }


        /// <summary>
        /// 根据Hash获取信息
        /// </summary>
        /// <param name="Hash"></param>
        /// <returns></returns>
        public ActionResult GetInfo(string Hash)
        {
            MongodbHelpers<AccountBook> block = new MongodbHelpers<AccountBook>();
            var list = block.QueryByFirst(a => a.Hash == Hash);
            //todo:验证节点是否匹配 
            //....
            if (list != null)
            {
                SelectBlock s = new SelectBlock();
                s.Msg = "ok";
                var mess = JsonConvert.DeserializeObject<UserRecordJson>(list.Data);
                s.Hash = list.Hash;
                s.TypeName = mess.Type == 0 ? "实验室" : mess.Type == 1 ? "电站" : "监造";
                s.OrderAddTime = mess.AddTime; //提交时间
                s.Mechanism = mess.Mechanism;
                s.TestMechanism = mess.TestMechanism;
                //区块信息
                s.Heigth = list.Height;
                s.AddTime = ToDate.To(list.TimeStamp).ToString("yyyy-MM-dd HH:mm:ss");
                s.PrevHash = list.PrevHash;
                s.FilePath = mess.FilePath;
                //共识状态
                List<PeerState> lp = new List<PeerState>();
                MongodbHelpers<PeerList> peer = new MongodbHelpers<PeerList>();
                var peerlist = peer.QueryAll();
                foreach (var peerList1 in peerlist)
                {
                    PeerState p = new PeerState();
                    p.name = peerList1.Account;
                    p.time = list.CreateTime;
                    p.state = 0;
                    lp.Add(p);
                }
                s.PeerState = lp;
                s.ProjecItem = mess.ProjecItem;
                s.NowPeer = mess.NowPeer;
                var peerList = peer.QueryOne(mess.NowPeer);
                if (peerList != null) s.NowPeerUrl = peerList.PeerUrl;
                return Json(s);
            }
            else
            {
                return Json(new Message() { Msg = "未找到", Status = 404 });
            }

        }


        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="hash"></param>
        /// <returns></returns>
        public ActionResult Print(string hash)
        {
            MongodbHelpers<AccountBook> block = new MongodbHelpers<AccountBook>();
            var list = block.QueryByFirst(a => a.Hash == hash);
            SelectBlock s = new SelectBlock();
            if (list != null)
            {

                s.Msg = "ok";
                s.Heigth = list.Height;
                s.Hash = list.Hash;
                s.AddTime = ToDate.To(list.TimeStamp).ToString("yyyy-MM-dd");
                var mess = JsonConvert.DeserializeObject<UserRecordJson>(list.Data);
                s.Mechanism = mess.Mechanism;
                s.TypeName = mess.Type == 0 ? "实验室" : mess.Type == 1 ? "电站" : "监造";
                s.FilePath = mess.FilePath;
                s.ProjecItem = mess.ProjecItem;
                s.NowPeer = mess.NowPeer;
                MongodbHelpers<PeerList> peer = new MongodbHelpers<PeerList>();
                var peerList = peer.QueryOne(mess.NowPeer);
                if (peerList != null) s.NowPeerUrl = peerList.PeerUrl;
                return View(s);
                //return Json(, JsonRequestBehavior.AllowGet);
            }
            else
            {
                s.Msg = "null";
                return View(s);
            }
        }


        /// <summary>
        /// 查询
        /// </summary>
        /// <returns></returns>
        public ActionResult List()
        {
            string value = "";
            HttpContext.Request.Cookies.TryGetValue("user", out value);
            //获取登录信息
            var user = GetUser.GetUserInfo(value);
            if (user != null)
            {
                return View(user);
            }
            else
            {
                return Redirect("/login");
            }
        }

        /// <summary>
        /// 客户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList(string name)
        {
            MongodbHelpers<AccountBook> block = new MongodbHelpers<AccountBook>();
            var list = block.QueryAll();
            var clist = list.Where(a => a.Data != null ? a.Data.Contains(name) : false).Take(20);
            List<CItem> lc = new List<CItem>();
            foreach (var item in clist)
            {
                try
                {
                    var mess = JsonConvert.DeserializeObject<UserRecordJson>(item.Data);
                    if (mess.Mechanism != null && mess.Mechanism.Contains(name))
                    {
                        CItem c = new CItem();
                        c.Name = mess.Mechanism;
                        c.addtime = mess.AddTime;
                        c.Hash = item.Hash;
                        lc.Add(c);
                    }

                }
                catch (Exception e)
                {
                    continue;
                    //throw;
                }

            }
            return Json(lc);
        }

        /// <summary>
        /// 获取证书信息
        /// </summary>
        /// <param name="hash"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetReportInfo(string hash)
        {
            MongodbHelpers<AccountBook> block = new MongodbHelpers<AccountBook>();
            var list = block.QueryByFirst(a => a.Hash == hash);
            SelectBlock s = new SelectBlock();
            if (list != null)
            {
                s.Msg = "ok";
                s.Heigth = list.Height;
                s.Hash = list.Hash;
                s.PrevHash = list.PrevHash;
                s.AddTime = ToDate.To(list.TimeStamp).ToString("yyyy-MM-dd");
                var mess = JsonConvert.DeserializeObject<UserRecordJson>(list.Data);
                s.OrderAddTime = mess.AddTime;
                s.Mechanism = mess.Mechanism;
                s.TestMechanism = mess.TestMechanism;
                s.TypeName = mess.Type == 0 ? "实验室" : mess.Type == 1 ? "电站" : "监造";
                if (mess.FilePath != null) {
                    s.FilePath = "http://121.43.191.79:4006/" + mess.FilePath;
                }
                s.ProjecItem = mess.ProjecItem;
                s.NowPeer = mess.NowPeer;
                MongodbHelpers<PeerList> peer = new MongodbHelpers<PeerList>();
                var peerList = peer.QueryOne(mess.NowPeer);
                if (peerList != null) s.NowPeerUrl = "http://121.43.191.79:4006/" + peerList.PeerUrl;
                //return View(s);
                return Json(s);
            }
            else
            {
                s.Msg = "不存在HASH,验证失败";
                return Json(s);
            }
        }

    }
}